//
//  HomeOwnViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import SwiftUI
class ChatListViewModel : BaseViewModel {
    
    // 枚举用于标识分组类型
    enum GroupedItem: Identifiable {
        case title(ChatListTitleBean)
        case data(AiRoleBean,String?)
        
        var id: String {
            switch self {
            case .title(let bean):
                return bean.id.uuidString
            case .data(let bean,let aiRoleOften):
                return bean.objectId ?? UUID().uuidString
            }
        }
    }
    
    @Published var items = [GroupedItem]()
    @Published var itemsRole = [AiRoleBean]()
    @Published var status = ""
    
    override init() {
        super.init()
        self.pageSize = 1000
        self.addObserve(self, .updateAiRole) { (selfInstance, update: Bool) in
            //刷新ai列表
            selfInstance.getData()
        }
        self.addObserve(self, .selectAiRole) { (selfInstance, update: Bool) in
            //刷新ai列表
            selfInstance.getData()
        }
        
    }
    
    
    
    func getData() {
        showLog("查询角色")
        requestList {
            let aiRoleOften = try await BackupsManager.shared.getDelegateConfig()?.getOften()
            
            var listAll: [GroupedItem] = []
            
            // 获取AI角色列表，如果为nil则使用空列表
            let list = try await BackupsManager.shared.getDelegateConfig()?.getAiRoleList(true) ?? []
            
            // 检查是否有选中项
            let isSelect = list.contains { $0.select }
            
            // 如果没有选中项且列表不为空，默认选中第一个
            if !isSelect, !list.isEmpty {
                list[0].select = true
            }
            
            // 筛选选中和未选中的角色
            let listSelect = list.filter { $0.select }
            let listNoSelect = list.filter { !$0.select }
            
            // 添加"已选定心灵"标题和对应角色
            listAll.append(.title(ChatListTitleBean(
                title: "已选定心灵",
                description: "已选定的心灵才能触发日记回复，来电，来信",
                count: listSelect.count
            )))
            listAll.append(contentsOf: listSelect.map {
                .data($0, aiRoleOften)
            })
            
            // 添加"未选定心灵"标题和对应角色
            listAll.append(.title(ChatListTitleBean(
                title: "未选定心灵",
                description: "",
                count: listNoSelect.count
            )))
            listAll.append(contentsOf: listNoSelect.map {
                .data($0, aiRoleOften)
            })
            return listAll
        } suc: {
            self.items = $0
            // 过滤出所有 .data 类型的元素，返回 [GroupedItem] 数组
            let dataItems = self.items.compactMap { item in
                if case .data(let bean, _) = item {
                    return bean
                }
                return nil
            }
            self.itemsRole = dataItems
            showLog($0)
        } fail: {
            let toast = $0.message
            showLog("获取角色列表报错：\(toast)")
            showToast(toast)
        }
    }
    
    func reset() {
        isInit = false
        items.removeAll()
    }
}
